import sys
from PyQt5 import QtWidgets, QtCore
import pyqtgraph as pg


class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()

        self.setWindowTitle('动态统计图展示')
        self.setGeometry(100, 100, 800, 600)

        # 创建主窗口的中心widget和layout
        self.central_widget = QtWidgets.QWidget()
        self.setCentralWidget(self.central_widget)
        self.layout = QtWidgets.QVBoxLayout(self.central_widget)

        # 创建一个用于放置图表的QTabWidget
        self.tab_widget = QtWidgets.QTabWidget()
        self.layout.addWidget(self.tab_widget)

        # 创建按钮用于添加和删除图表
        self.button_layout = QtWidgets.QHBoxLayout()
        self.add_button = QtWidgets.QPushButton("添加图表")
        self.add_button.clicked.connect(self.add_plot)
        self.remove_button = QtWidgets.QPushButton("删除当前图表")
        self.remove_button.clicked.connect(self.remove_plot)
        self.button_layout.addWidget(self.add_button)
        self.button_layout.addWidget(self.remove_button)
        self.layout.addLayout(self.button_layout)

        # 初始化一个默认图表
        self.add_plot()

    def add_plot(self):
        # 创建一个新的PlotWidget
        plot_widget = pg.PlotWidget()
        plot_widget.setTitle("新图表", color='#008080', size='12pt')
        plot_widget.setLabel("left", "值")
        plot_widget.setLabel("bottom", "时间")
        plot_widget.setBackground('w')

        # 添加一些示例数据
        x_data = [1, 2, 3, 4, 5]
        y_data = [10, 15, 7, 12, 9]
        plot_widget.plot(x_data, y_data, pen=pg.mkPen('b'))

        # 将PlotWidget添加到QTabWidget中
        self.tab_widget.addTab(plot_widget, f"图表 {self.tab_widget.count() + 1}")

    def remove_plot(self):
        # 删除当前选中的图表
        current_index = self.tab_widget.currentIndex()
        if current_index >= 0:
            self.tab_widget.removeTab(current_index)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    app.exec_()
